import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_model/home/module_detail_model.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../hj_utils/api_service/vid_service.dart';

class PicGridLogic extends GetxController with GetTickerProviderStateMixin {
  AllSection? section;
  List<VideoModel>? allMediaInfo; //海角样式
  final List<String> tabs = ['最多观看', '最新发布', '最多收藏'];
  final sortTypes = ['wtach', 'new', 'collect'];
  int currentPage = 1;
  RefreshController refreshCtr = RefreshController();

  late TabController tabCtr = TabController(
    initialIndex: 0,
    length: tabs.length,
    vsync: this,
  )..addListener(() {
      if (!tabCtr.indexIsChanging) {
        onChangesortIndex();
      }
    });

  PicGridLogic({this.section});

  onReady() {
    super.onReady();
    loadData(); //获取
  }

  //0、综合 1、最新 2、最多播放量 3、最多喜欢
  loadData({int pageNum = 1}) async {
    allMediaInfo ??= [];
    if (section?.type == -100 || section?.type == -101) {
      loadSpecailData(pageNum: pageNum);
    } else {
      loadListData(pageNum: pageNum);
    }
  }

  loadMoreData() => loadData(pageNum: currentPage + 1);

  //获取最新/推荐
  loadSpecailData({int pageNum = 1}) async {
    final result = await VidService.getModuleDetail(
      section?.sectionID ?? '',
      pageNumber: pageNum,
      pageSize: 10,
      moduleSort: section?.type == -100 ? 2 : 1,
    );

    if (result != null) {
      if (pageNum == 1) allMediaInfo?.clear();
      currentPage = pageNum;
      allMediaInfo?.addAll(result.allVideoInfo ?? []); //设置海角样式列表
      update(['list']);
    }
    refreshCtr.refreshCompleted();
    result?.hasNext == true ? refreshCtr.loadComplete() : refreshCtr.loadNoData();
  }

  loadListData({int pageNum = 1}) async {
    final result = await VidService.fetchSectionVideos(
      section?.sectionID ?? '',
      pageNumber: pageNum,
      pageSize: 10,
      sortType: sortTypes[tabCtr.index],
    );

    if (result != null) {
      if (pageNum == 1) allMediaInfo?.clear();
      currentPage = pageNum;
      allMediaInfo?.addAll(result.videos ?? []); //设置海角样式列表
    }
    update(['list']);
    refreshCtr.refreshCompleted();
    result?.hasNext == true ? refreshCtr.loadComplete() : refreshCtr.loadNoData();
  }

  //全列表排序，loading
  onChangesortIndex() async {
    allMediaInfo = null;
    update();
    Future.delayed(Duration(milliseconds: 50)).then((value) => loadData());
  }
}
